package com.wangyadong.hobby.concurrent;

import com.wangyadong.hobby.test.People;

import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;
import java.util.stream.IntStream;

public class AtomicFieldTest {
    static volatile People people = new People(10, "wyd");

    public static void testReferenceWithCompareAndSet() {
        AtomicReference<People> atomicReference = new AtomicReference<>(people);
        IntStream.range(1, 10).forEach(i -> {
            new Thread(() -> {
                final People people = atomicReference.get();
                if (atomicReference.compareAndSet(people, new People(people.getAge() + 10, "wyd"))) {
                    System.out.println("线程" + Thread.currentThread().getName() + " " + people.getName() + "年龄=" + people.getAge());
                } else {
                    System.out.println("线程" + Thread.currentThread().getName() + " " + "try again");
                }
            }).start();
        });
    }

    public static void testReferenceWithGetAndSet() {
        AtomicReference<People> atomicReference = new AtomicReference<>(people);
        People initpeople = atomicReference.get();
        assert initpeople.getAge() == 10;
        People wyd = atomicReference.getAndSet(new People(people.getAge() + 10, "wyd"));
        assert wyd.getAge() == 10;
        People people1 = atomicReference.get();
        assert people1.getAge() == 20;
    }

    public static void main(String[] args) {
        testReferenceWithGetAndSet();

    }


}
